package logic

import (
	"cart_srv/models/redis"
	"context"
	"errors"
	"fmt"
	"strconv"

	"cart_srv/cart_srv"
	"cart_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListCartLogic {
	return &ListCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListCartLogic) ListCart(in *cart_srv.ListCartRequest) (*cart_srv.ListCartResponse, error) {
	// todo: add your logic here and delete this line
	if redis.CartIsNilOrNotNil(int(in.UserId)) {
		return nil, errors.New("购物车为空")
	}
	cart := redis.ListCart(int(in.UserId))
	var sli []*cart_srv.Cart
	for _, s := range cart {
		val := redis.Rdb.HGetAll(redis.Ctx, s).Val()
		var one cart_srv.Cart
		fmt.Println(val["goods_name"], in.GoodsName)
		if in.GoodsName != "" && val["goods_name"] == in.GoodsName {
			num, _ := strconv.Atoi(val["goods_num"])
			price, _ := strconv.ParseFloat(val["goods_price"], 64)
			one = cart_srv.Cart{
				Num:        int64(num),
				GoodsName:  val["goods_name"],
				GoodsCover: val["goods_cover"],
				GoodsIntro: val["goods_intro"],
				GoodsPrice: float32(price),
			}
			fmt.Println("走if")
			sli = append(sli, &one)
		} else if in.GoodsName == "" {
			num, _ := strconv.Atoi(val["goods_num"])
			price, _ := strconv.ParseFloat(val["goods_price"], 64)
			one = cart_srv.Cart{
				Num:        int64(num),
				GoodsName:  val["goods_name"],
				GoodsCover: val["goods_cover"],
				GoodsIntro: val["goods_intro"],
				GoodsPrice: float32(price),
			}
			fmt.Println("走else")
			sli = append(sli, &one)
		}
	}
	return &cart_srv.ListCartResponse{Cart: sli}, nil
}
